package com.atguigu.gateway.predicate;

import jakarta.validation.constraints.NotEmpty;
import org.springframework.cloud.gateway.handler.predicate.AbstractRoutePredicateFactory;
import org.springframework.cloud.gateway.handler.predicate.HeaderRoutePredicateFactory;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.server.ServerWebExchange;

import java.util.Arrays;
import java.util.List;
import java.util.function.Predicate;

/**
 * @Author: change
 * @Date: 2025/04/14 18:10
 */
@Component
public class VipRoutePredicateFactory extends AbstractRoutePredicateFactory<VipRoutePredicateFactory.Config> {
	
	
	public VipRoutePredicateFactory() {
		super(Config.class);
	}
	
	/**
	 * 断言逻辑判断
	 * @param config
	 * @return
	 */
	
	@Override
	public Predicate<ServerWebExchange> apply(VipRoutePredicateFactory.Config config) {
		
		return serverWebExchange -> {
			ServerHttpRequest request = serverWebExchange.getRequest();
			String first = request.getQueryParams().getFirst(config.getParam());
			return StringUtils.hasText(first) && first.equals(config.getValue());
		};
	}
	
	@Override
	public List<String> shortcutFieldOrder() {
		return Arrays.asList("param","value");
	}
	
	@Validated
	public static class Config {
		
		@NotEmpty
		private String param;
		
		@NotEmpty
		private String value;
		
		
		public String getParam() {
			return param;
		}
		
		public void setParam(String param) {
			this.param = param;
		}
		
		public String getValue() {
			return value;
		}
		
		public void setValue(String value) {
			this.value = value;
		}
	}
}
